import {
  apiCmsmqGetBuyList,
  apiPurtcAdd,
  cmsmgLatestExchangeRate,
  cmsmvPurchaseStaffList,
  cmsnaPurchaseVoList,
  purtblList,
} from '@/api/url/salesOrderManagement';
import router from '@/router';
import { hongzucategoriesTaxesList } from '@/utils/base';
import { EFTimeFormatConversion, arrayStatistics, debounce, deepCopy, formatDate, isNullPm, isTimeInInterval } from '@/utils/baseMethods';
import { divisionMethod, multiplication, relativeAddition, subtraction } from '@/utils/calculationFormula';
import notification from '@arco-design/web-vue/es/notification';

import { reactive, watch } from 'vue';
import { VXETable } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
export default function importConfig() {
  const base = reactive<any>({
    tabelList: null,
    supplierList: [],
    topTitle: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 100,
    },
    purchaseOrderList: [],
    supplierOptionList: [],
    supplierOptionListCopy: [],
    currencyList: [],
    singleDataList: [],
    featureData: null,
    defaultSelecteRowKeys: null,
    exchangeRate: 7.3,
    amountOption: null,
    purchasingOption: null,
    paymentTerms: null,
  });

  const init = () => {
    getTable();
    purchaseOrder();
    supplierView();
    currencyListOption();
    exchangeRateAcquisition();
    purchasingStaff();
    cmsnaPurchasenpm();
  };

  /**
   * @exports getTable 表单数据获取,获取数据源头 localStorage 中的BLISOK
   */
  const getTable = () => {
    /**
     * @exports mergingMethod 预设规则获取
     * @param sectionTime 预交货起始日期加结束日期
     * @param mergingMethod 合并方式
     * @param primaryMeter 主表备注
     * @param sublist 子表备注
     */
    base.featureData = JSON.parse(router.currentRoute.value.query.featureData as any);
    base.tabelList = [];
    JSON.parse(localStorage.getItem('BLISOK') as any).map((res: any) => {
      res.getOmnList.map((reb: any) => {
        reb.purchaseNumber = reb.number;
        reb.productId = reb.productNumber;
        reb.specification = reb.specifications;
        res.taxRate = isNullPm(res.taxRate) ? 0 : multiplication({ x: res.taxRate, y: 100 });
        reb.remarkpsan = [];
        reb.remarkCopy = null;
        delete reb.singleSerialNumber;
        delete reb.time;
        delete reb.productNumber;
        delete reb.specifications;
        delete reb.unitPrice;
        reb.remark = base.featureData.sublist ? reb.remark : null;
        reb.remarkCopy = reb.remark;
        // res.paymentId = reb.paymentId;
        // res.payment = reb.payment;
        base.tabelList.push(reb);
      });
      console.log(base.tabelList);
    });

    /**
     * 收集所有供应商
     */
    const steamSupplierList: any = [];
    /**
     * 采购单头相同供应商数据数据载入,并处理时间格式,已经税种格式
     */
    base.tabelList.map((res: any) => {
      if (!isNullPm(res.deliveryDate)) res.deliveryDate = EFTimeFormatConversion(res.deliveryDate);
      if (!isNullPm(res.requirementDate)) res.requirementDate = EFTimeFormatConversion(res.requirementDate);
      res.taxRate = isNullPm(res.taxRate) ? 0 : multiplication({ x: res.taxRate, y: 100 });
      steamSupplierList.push(res.supplierNo);
    });
    /**
     * 过滤出所有供应商
     */
    base.supplierList = arrayStatistics(steamSupplierList);
    distributionGetTable();
    singleDataLoad();
  };

  /**
   * @exports menuConfig 表单配置器
   */
  const menuConfig = reactive<any>({
    className: 'my-menus',
    header: {
      options: [[{ code: 'exportAll', name: '导出所有.csv' }]],
    },
    body: {
      options: [
        [
          { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' },
          { code: 'addLine', name: '在最下面添加一行', prefixIcon: 'vxe-icon-success-circle-fill', className: 'my-copy-item' },
          { code: 'deleteLine', name: '删除此行', prefixIcon: 'vxe-icon-delete-fill', className: 'my-copy-item' },
        ],
      ],
    },
    footer: {
      options: [[{ code: 'clearAll', name: '清空数据' }]],
    },
  });

  const menuBodyConfig = reactive<any>({
    className: 'my-menus',
    header: {
      options: [[{ code: 'exportAll', name: '导出所有.csv' }]],
    },
    body: {
      options: [
        [{ code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }],
        [{ code: 'deleteLine', name: '删除此行', prefixIcon: 'vxe-icon-delete-fill', className: 'my-copy-item' }],
      ],
    },
    footer: {
      options: [[{ code: 'clearAll', name: '清空数据' }]],
    },
  });

  /**
   * @exports distributionGetTable 表单数据载入,并在这边处理备注信息,通过同供应商数据的剔除生成采购单头的数据
   * currency 币别编号
   */
  const distributionGetTable = () => {
    base.topTitle = [];

    base.supplierList.map((res: any, index: any) => {
      for (let a = 0; a <= base.tabelList.length - 1; a++) {
        if (base.tabelList[a].supplierNo == res.label) {
          base.topTitle.push({
            valueNo: index + 1,
            supplierNo: base.tabelList[a].supplierNo,
            supplierName: base.tabelList[a].supplierName,
            vendorDataPartition: null,
            currency: base.tabelList[a].currency,
            taxCategory: base.tabelList[a].taxCategory,
            taxRate: isNullPm(base.tabelList[a].taxRate) ? 0 : base.tabelList[a].taxRate,
            remark: base.featureData.primaryMeter ? base.tabelList[a].headRemark : null,
            requirementDate: formatDate(new Date(), 'yyyy-MM-dd'),
            totalNumber: 0,
            totalTax: 0,
            totalAmount: 0,
            purchaseAmount: 0,
            purchaserNo: base.tabelList[a].purchaserNo,
            amountBeforeTax: 0,
            paymentId: base.tabelList[a].paymentId,
            payment: base.tabelList[a].payment,
          });
          break;
        }
      }
    });
  };

  /**
   * @exports headerComputer 表单税率计算全部
   */
  const headerComputer = () => {
    /**
     * 重置数据
     */
    base.singleDataList.map((res: any) => {
      base.topTitle[res.valueNo - 1].totalNumber = 0;
      base.topTitle[res.valueNo - 1].totalTax = 0;
      base.topTitle[res.valueNo - 1].totalAmount = 0;
      base.topTitle[res.valueNo - 1].purchaseAmount = 0;
      /**
       * amountBeforeTax 税前金额
       */
      base.topTitle[res.valueNo - 1].amountBeforeTax = 0;
    });
    base.singleDataList.map((res: any) => {
      base.topTitle[res.valueNo - 1].totalNumber = relativeAddition({
        x: base.topTitle[res.valueNo - 1].totalNumber,
        y: res.purchaseNumber,
      });
      base.topTitle[res.valueNo - 1].totalTax = relativeAddition({
        x: base.topTitle[res.valueNo - 1].totalTax,
        y: res.taxMoney,
      });
      base.topTitle[res.valueNo - 1].totalAmount = relativeAddition({ x: base.topTitle[res.valueNo - 1].totalAmount, y: res.totalAmount });
      base.topTitle[res.valueNo - 1].purchaseAmount = relativeAddition({
        x: base.topTitle[res.valueNo - 1].purchaseAmount,
        y: subtraction({ x: res.totalAmount, y: res.taxMoney }) as any,
      });
    });
    amountData();
  };

  /**
   * @exports singleDataLoad 加载单身数据
   */
  const singleDataLoad = () => {
    const steam: any = [];
    base.supplierList.map((res: any, index: any) => {
      base.tabelList.map((reb: any) => {
        if (res.label == reb.supplierNo) {
          reb.valueNo = index + 1;
          steam.push(reb);
        }
      });
    });
    base.singleDataList = steam;
    ruleLoading();
  };

  /**
   * @exports ruleLoading 页面数据规则载入器
   */
  const ruleLoading = () => {
    /**
     * @param sectionTime 预交货起始日期加结束日期
     * @param mergingMethod 合并方式
     * @param primaryMeter 主表备注
     * @param sublist 子表备注
     */
    if (!isNullPm(base.featureData.sectionTime[0]) && !isNullPm(base.featureData.sectionTime[1])) sectionTimeMethod();
    else if (base.featureData.mergingMethod == '同供应商同品号合并(无视时间区间)') mergeInventoryNumberData();
    else if (base.featureData.mergingMethod == '同供应商同单据合并') mergeWithSuppliersDocuments();
    dataCalculator();
    headerComputer();
  };
  /**
   * @exports sectionTimeMethod 预交货起始日期加结束日期规则载入
   */
  const sectionTimeMethod = () => {
    const coincidentSteam: any = [];
    const inconformitytSteam: any = [];
    base.singleDataList.map((res: any) => {
      if (isTimeInInterval(base.featureData.sectionTime[0], base.featureData.sectionTime[1], res.deliveryDate)) {
        coincidentSteam.push(res);
      } else {
        inconformitytSteam.push(res);
      }
    });

    base.singleDataList = inconformitytSteam.concat(conformToSteam(coincidentSteam));
  };

  /**
   * @exports conformToSteam 符合数据处理
   */
  const conformToSteam = (param) => {
    const setam: any = [];
    param.map((res: any) => {
      if (base.featureData.mergingMethod == '同供应商同品号合并(无视时间区间)') {
        setam.push(res.productId + res.productName);
      } else if (base.featureData.mergingMethod == '同供应商同单据合并') {
        setam.push(res.requisitionType + res.requisitionNo + res.productId + res.productName);
      } else {
        setam.push(res.productId + res.productName);
      }
    });
    const handleSetam = arrayStatistics(setam);
    let tidyUpList: any = [];
    handleSetam.map((res: any, index: any) => {
      /**
       * @exports numericMark 自增数据用来标记我实际已经得到的数据条数
       */
      let numericMark = 0;
      base.singleDataList.map((reb: any) => {
        let steampsan = null;
        let remarkpsan = null;

        if (!isNullPm(reb.purtbSummary)) steampsan = deepCopy(reb.purtbSummary);
        if (!isNullPm(reb.remarkpsan)) remarkpsan = deepCopy(reb.remarkpsan);
        if (isNullPm(reb.currency)) reb.currency = 'RMB';

        if (
          reb.productId + reb.productName == res.label ||
          reb.requisitionType + reb.requisitionNo + reb.productId + reb.productName == res.label
        ) {
          if (numericMark == 0) {
            tidyUpList.push(reb);
            reb.purtbNumSummary = [];
            reb.purtbSummary = [];
            /**
             * @param  purtbNumSummary 请购单单身 请购数量汇总
             */
            reb.purtbNumSummary.push(reb.purchaseNumber);
            reb.purtbSummary.push(`${reb.requisitionType}-${reb.requisitionNo}-${reb.requisitionNumber}`);
            let staem: any = null;
            if (isNullPm(reb.remarkCopy)) staem = `请购来自:${reb.requisitionType}-${reb.requisitionNo}-${reb.requisitionNumber}`;
            else staem = `请购来自:${reb.requisitionType}-${reb.requisitionNo}-${reb.requisitionNumber}(${reb.remarkCopy})`;
            reb.remarkpsan.push(staem);
          }

          if (numericMark > 0) {
            tidyUpList[index].purchaseNumber += reb.purchaseNumber;
            tidyUpList[index].purtbNumSummary.push(reb.purchaseNumber);
            tidyUpList[index].purtbSummary.push(`${reb.requisitionType}-${reb.requisitionNo}-${reb.requisitionNumber}`);
            let staem: any = null;
            if (isNullPm(reb.remark)) staem = `请购来自:${reb.requisitionType}-${reb.requisitionNo}-${reb.requisitionNumber}`;
            else staem = `请购来自:${reb.requisitionType}-${reb.requisitionNo}-${reb.requisitionNumber}(${reb.remarkCopy})`;
            tidyUpList[index].remarkpsan.push(staem);
          }
          numericMark++;
          if (!isNullPm(steampsan)) {
            const saytae = tidyUpList[index].purtbSummary.concat(steampsan);
            const acjio = Array.from(new Set(saytae));
            tidyUpList[index].purtbSummary = acjio;
          }
          if (!isNullPm(remarkpsan)) {
            const saytae = tidyUpList[index].remarkpsan.concat(remarkpsan);
            const acjio: any = Array.from(new Set(saytae));
            tidyUpList[index].remarkpsan = acjio;
          }
          if (numericMark == reb.value) {
            numericMark = 0;
          }
        }
      });
    });

    tidyUpList = remarkProcessing(deepCopy(tidyUpList));
    return tidyUpList;
  };

  /**
   * @exports mergeInventoryNumberData 同品号合并
   */
  const mergeInventoryNumberData = () => {
    base.singleDataList = conformToSteam(deepCopy(base.singleDataList));
  };

  const selectAllChangeEvent = ({ checked }) => {
    const $table = base.tableRef;
    if ($table) {
      const records = $table.getCheckboxRecords();
      console.log(checked ? '所有勾选事件' : '所有取消事件', records);
    }
  };

  const selectChangeEvent = ({ checked }) => {
    const $table = base.tableRef;
    if ($table) {
      const records = $table.getCheckboxRecords();
      console.log(checked ? '勾选事件' : '取消事件', records);
    }
  };

  /**
   * @exports purchaseOrder 采购单别下拉接口
   */
  const purchaseOrder = () => {
    apiCmsmqGetBuyList('').then((res: any) => {
      if (res.code == '200') base.purchaseOrderList = res.data;
    });
  };

  /**
   * @exports supplierView 供应商下拉接口
   */
  const supplierView = () => {
    purtblList('').then((res: any) => {
      if (res.code == '200') {
        base.supplierOptionList = res.data;
        base.supplierOptionListCopy = [];
        base.supplierOptionList.map((reb: any) => {
          Object.keys(reb).map((rea: any) => {
            if (!isNullPm(reb[rea]) && typeof reb[rea] == 'string') reb[rea] = reb[rea].trim();
          });
        });
        for (let a = 0; a < 20; a++) {
          base.supplierOptionListCopy.push(base.supplierOptionList[a]);
        }
      }
    });
  };

  /**
   * @exports vendorDataPartition 供应商下拉列表数据分流
   * @param param
   * @param key
   */
  const vendorDataPartition = (param, key) => {
    const steam: any = [];
    let numberPim = 0;
    for (let a = 0; a <= base.supplierOptionList.length - 1; a++) {
      if (base.supplierOptionList[a][key].indexOf(param) != -1 && numberPim <= 20) {
        steam.push(base.supplierOptionList[a]);
        numberPim++;
      } else if (numberPim > 20) {
        break;
      }
    }
    base.supplierOptionListCopy = steam;
  };

  /**
   * @exports filterMethod  供应商接口输入时调起数据分流,分流数据
   * @param param
   * @param key
   */
  const filterMethod = (param, key) => {
    vendorDataPartition(param, key);
  };

  const inputTion = () => {};

  /**
   * @exports clickSupplier 供应商下拉数据双向绑定
   * @param item
   * @param rowIndex
   */
  const clickSupplier = (item, rowIndex) => {
    base.topTitle[rowIndex].supplierNo = item.supplierNo;
    base.topTitle[rowIndex].supplierName = item.supplierName;
    base.topTitle[rowIndex].taxRate = multiplication({ x: item.taxRate, y: 100 });
    base.topTitle[rowIndex].paymentId = item.paymentId;
    base.topTitle[rowIndex].payment = item.payment;
    let steam: any = null;
    base.purchasingOption.some((src) => {
      if (src.mv002 == item.purchaseStaff) steam = src;
    });
    if (isNullPm(steam)) {
      steam = 'Default_No';
    } else {
      steam = steam.mv001;
    }
    base.topTitle[rowIndex].purchaserNo = steam;
    base.topTitle[rowIndex].currency = item.currency;
    bodySupplierView(item, base.topTitle[rowIndex].valueNo);
  };

  /**
   * @exports currencyListOption 币种数据插入
   * @param param
   */
  const currencyListOption = () => {
    const steam = [
      {
        value: 'RMB',
        label: '人民币',
      },
      {
        value: 'USD',
        label: '美元',
      },
    ];
    base.currencyList = steam;
  };

  /**
   * @exports clickTaxCategory 税种下拉确认后绑定税率,并替换所有同组的税种数据
   */
  const clickTaxCategory = (item, rowIndex) => {
    // base.topTitle[rowIndex].taxRate = item.taxRate
    base.singleDataList.map((res: any) => {
      if (res.valueNo == base.topTitle[rowIndex].valueNo) {
        res.taxCategory = item.value;
        res.taxRate = multiplication({ x: item.taxRate, y: 100 });
      }
    });
    headerComputer();
  };
  /**
   * @exports clickCurrency 币种确认后替换同组的所有币种
   */
  const clickCurrency = (item, rowIndex) => {
    base.singleDataList.map((res: any) => {
      if (res.valueNo == base.topTitle[rowIndex].valueNo) {
        res.currency = item.value;
      }
    });
    ruleLoading();
  };

  /**
   * @exports clickCurrency 币种确认后替换同组的所有币种
   */
  const clickCategoriesTaxes = (item, rowIndex) => {
    base.singleDataList.map((res: any) => {
      if (res.valueNo == base.topTitle[rowIndex].valueNo) {
        res.taxCategory = item.value;
      }
    });
    ruleLoading();
  };

  /**
   * @exports clickTaxRate 币种确认后替换同组的所有币种
   */
  const clickTaxRate = (item, rowIndex) => {
    base.singleDataList.map((res: any) => {
      if (res.valueNo == base.topTitle[rowIndex].valueNo) {
        res.taxRate = item;
      }
    });
    ruleLoading();
  };

  /**
   * @exports contextMenuClickEvent 表单操作格式
   * @param param0
   */
  const contextMenuClickEvent = ({ menu, row, column }) => {
    switch (menu.code) {
      case 'copy':
        // 示例
        if (row && column) {
          if (XEClipboard.copy(row[column.field])) {
            VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
          }
        }
        break;
      case 'addLine':
        // 示例
        topTitleAddLine();
        break;
      case 'deleteLine':
        // 示例
        topTitleDeleteLine(row);
        break;

      default:
        console.log(`点击了 ${menu.name} 选项`, row, column, row[column.field]);
    }
  };

  /**
   * @exports contextMenuBodyClickEvent 表单操作格式
   * @param param0
   */
  const contextMenuBodyClickEvent = ({ menu, row, column }) => {
    switch (menu.code) {
      case 'copy':
        // 示例
        if (row && column) {
          if (XEClipboard.copy(row[column.field])) {
            VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
          }
        }
        break;
      case 'deleteLine':
        // 示例
        singleDataListOption(row);
        break;
      default:
        console.log(`点击了 ${menu.name} 选项`, row, column, row[column.field]);
    }
  };

  /**
   * @exports topTitleAddLine 列表添加行操作
   */
  const topTitleAddLine = () => {
    base.topTitle.push({
      valueNo: base.topTitle.length + 1,
      supplierNo: null,
      supplierName: null,
      vendorDataPartition: null,
      currency: null,
      taxCategory: null,
      taxRate: null,
      remark: null,
    });
    base.supplierList = [];
    base.topTitle.map((res: any) => {
      base.supplierList.push(res.supplierNo);
    });
    base.topTitle.sort();
  };

  /**
   * @exports topTitleDeleteLine 列表删除行操作
   */
  const topTitleDeleteLine = (row) => {
    base.topTitle.splice(row.valueNo - 1, 1);
    base.topTitle.map((res: any, index: any) => {
      res.valueNo = index + 1;
    });
    base.singleDataList.map((res: any, index: any) => {
      if (res.valueNo == row.valueNo) {
        base.singleDataList.splice(index, 1);
      }
    });
    base.topTitle.sort();
    base.singleDataList.sort();
  };

  /**
   * @exports singleDataListOption 列表删除行操作
   */
  const singleDataListOption = (row) => {
    base.singleDataList.splice(row.valueNo - 1, 1);
    base.singleDataList.map((res: any, index: any) => {
      res.valueNo = index + 1;
    });
    base.singleDataList.sort();
  };

  /**
   * @exports bodySupplierView 单头供应商数据变更的同时,修正单身的供应商数据
   */
  const bodySupplierView = (item, valueNo) => {
    base.singleDataList.map((res: any) => {
      if (res.valueNo == valueNo) {
        res.supplierNo = item.supplierNo;
        res.supplierName = item.supplierName;
        res.taxRate = multiplication({ x: item.taxRate, y: 100 });
        res.currency = item.currency;
      }
    });
    ruleLoading();
  };

  /**
   * @exports clickValueNom 单身采购编号变更时,同时去改变数据本身的供应商信息
   */
  const clickValueNom = (item, rowIndex) => {
    base.singleDataList[rowIndex].supplierNo = base.topTitle[item - 1].supplierNo;
    base.singleDataList[rowIndex].supplierName = base.topTitle[item - 1].supplierName;
    base.singleDataList[rowIndex].currency = base.topTitle[item - 1].currency;
    base.singleDataList[rowIndex].taxRate = multiplication({ x: base.topTitle[item - 1].taxRate, y: 100 });
    base.singleDataList.sort();
  };

  /**
   * @exports creatorPurtcAdd 采购单新增接口
   */
  const creatorPurtcAdd = () => {
    const steam: any = {
      procureDtoList: [],
    };
    base.topTitle.map((res: any) => {
      let steamDom: any = {};
      steamDom = {
        creator: 'ERP',
        purtdList: [],
        coinType: res.currency,
        documentDate: formatDate(new Date(), 'yyyyMMdd'),
        exchangeRate: res.currency == 'USD' ? base.exchangeRate : 1,
        purchaseDate: res.requirementDate.replace(/\-/g, ''),
        remark: res.remark,
        supplier: res.supplierNo,
        supplierName: res.supplierName,
        tax: multiplication({ x: 0.01, y: res.taxRate }),
        taxType: res.taxCategory,
        type: res.vendorDataPartition,
        totalNumber: res.totalNumber,
        totalTax: res.totalTax,
        totalAmount: res.totalAmount,
        purchaseAmount: res.purchaseAmount,
        purchaserNo: res.purchaserNo,
        purchaserName: res.purchaserName,
        payment: res.payment,
        paymentId: res.paymentId,
        shippingAddressOne: res.shippingAddressOne,
      };
      const oppstaem = JSON.parse(JSON.stringify(base.singleDataList));
      oppstaem.map((reb: any) => {
        if (reb.supplierNo == res.supplierNo) {
          reb.purchaseNumSummary = reb.purtbNumSummary;
          let comun = 0;
          if (!isNullPm(reb.purtbNumSummary)) {
            reb.purtbNumSummary.map((rep: any) => {
              comun += rep;
            });
            if (reb.purchaseNumber != comun) {
              const topNumber = reb.purchaseNumber - comun;
              reb.purchaseNumSummary[reb.purchaseNumSummary.length - 1] += topNumber;
            }
          }
          reb.purchaseNumSummary = res.purchaseNumSummary?.join(',');
          reb.purtbNumSummary = res.purtbNumSummary?.join(',');
          reb.purtbSummary = reb.purtbSummary?.join(',');
          reb.supplier = reb.supplierNo;
          reb.deliveryDate = reb.deliveryDate?.replace(/\-/g, '');
          reb.taxRate = multiplication({ x: 0.01, y: reb.taxRate });
          reb.tax = reb.taxMoney;
          reb.purchaseAmount = reb.totalAmount;
          delete reb.number;
          delete reb.totalAmount;
          delete reb.supplierNo;
          delete reb.supplierName;
          delete reb.currency;
          delete reb.taxCategory;
          delete reb.requirementDate;
          delete reb.purchaserNo;
          delete reb.purchaserName;
          delete reb.requisitionType;
          delete reb.requisitionNo;
          delete reb.requisitionNumber;
          delete reb.urgentCode;
          delete reb.purchasedQuantity;
          delete reb.productNumber;
          delete reb.headRemark;
          delete reb.uuid;
          delete reb._X_ROW_KEY;
          delete reb.valueNo;
          delete reb.status;
          delete reb.supplier;
          delete reb.referencePrice;
          delete reb.taxMoney;
          delete reb.remarkpsan;
          delete reb.remarkCopy;
          steamDom.purtdList.push(reb);
        }
      });
      if (!isNullPm(steamDom?.creator)) steam.procureDtoList.push(steamDom);
    });
    if (submitCheck(steam))
      apiPurtcAdd(steam).then((res: any) => {
        if (res.code == 200) {
          notification.success({
            title: '消息通知',
            content: '采购单生成成功~',
          });
          notification.info({
            title: '消息通知',
            content: res.data,
            duration: 5000,
          });
          router.push('/buyingRequisition');
          localStorage.removeItem('BLISOK');
        }
      });
  };

  /**
   * @exports dataCalculator 数据金额计算器
   */
  const dataCalculator = () => {
    base.singleDataList.map((res: any, index: any) => {
      if (isNullPm(res.purchaseNumber)) res.purchaseNumber = 0;
      if (isNullPm(res.purchasePrice)) res.purchasePrice = 0;
      if (isNullPm(res.taxMoney)) res.taxMoney = 0;
      summaryCalculationFormulas(index);
    });
    base.singleDataList.sort();
  };

  /**
   * @exports debounceFunction 防抖集成
   */
  const debounceFunction = debounce((rowIndex) => {
    summaryCalculationFormulas(rowIndex);
  }, 100);

  const summaryCalculationFormulas = (rowIndex) => {
    if (isNullPm(base.singleDataList[rowIndex].purchaseNumber)) base.singleDataList[rowIndex].purchaseNumber = 0;
    if (isNullPm(base.singleDataList[rowIndex].purchasePrice)) base.singleDataList[rowIndex].purchasePrice = 0;
    else base.singleDataList[rowIndex].purchasePrice = Number(base.singleDataList[rowIndex].purchasePrice);

    /**
     * taxRate 税率
     * taxCategory 税种
     * @param totalPrice 总金额
     */
    const totalPrice: any = multiplication({
      x: base.singleDataList[rowIndex].purchaseNumber,
      y: base.singleDataList[rowIndex].purchasePrice,
    });
    const tax: any = multiplication({ x: 0.01, y: base.singleDataList[rowIndex].taxRate });
    const taxRate: any = multiplication({
      x: totalPrice,
      y: tax,
    });
    if (base.singleDataList[rowIndex].taxCategory == 1) {
      // if (base.singleDataList[rowIndex].currency == 'USD') {
      //   const steam: any = multiplication({ x: totalPrice, y: base.exchangeRate });
      //   base.singleDataList[rowIndex].totalAmount = steam;
      //   base.singleDataList[rowIndex].taxMoney = multiplication({
      //     x: 0.01,
      //     y: multiplication({ x: steam, y: base.singleDataList[rowIndex].taxRate }) as any,
      //   });
      // } else {
      const onewTax: any = divisionMethod({ x: totalPrice, y: relativeAddition({ x: 1, y: tax }) });
      base.singleDataList[rowIndex].totalAmount = totalPrice;
      base.singleDataList[rowIndex].taxMoney = subtraction({ x: totalPrice, y: onewTax });
      // }
    } else if (base.singleDataList[rowIndex].taxCategory == 2) {
      // if (base.singleDataList[rowIndex].currency == 'USD') {
      //   const steam: any = multiplication({ x: totalPrice, y: base.exchangeRate });
      //   base.singleDataList[rowIndex].totalAmount = relativeAddition({
      //     x: steam,
      //     y: multiplication({ x: 0.01, y: multiplication({ x: steam, y: base.singleDataList[rowIndex].taxRate }) as any }) as any,
      //   });
      //   base.singleDataList[rowIndex].taxMoney = multiplication({
      //     x: 0.01,
      //     y: multiplication({ x: steam, y: base.singleDataList[rowIndex].taxRate }),
      //   } as any);
      // } else {
      base.singleDataList[rowIndex].totalAmount = relativeAddition({
        x: totalPrice,
        y: multiplication({ x: 0.01, y: multiplication({ x: totalPrice, y: base.singleDataList[rowIndex].taxRate }) as any }) as any,
      });
      base.singleDataList[rowIndex].taxMoney = multiplication({
        x: 0.01,
        y: multiplication({ x: totalPrice, y: base.singleDataList[rowIndex].taxRate }),
      } as any);
      // }
    } else {
      base.singleDataList[rowIndex].totalAmount = totalPrice;
      base.singleDataList[rowIndex].taxMoney = 0;
    }
    /**
     * 税前金额永远是总金额减去税额
     */
    base.singleDataList[rowIndex].amountBeforeTax = subtraction({
      x: base.singleDataList[rowIndex].totalAmount,
      y: base.singleDataList[rowIndex].taxMoney,
    });
    headerComputer();
  };

  /**
   * @exports timeCalculation 总金额计算器
   * @returns
   */
  const timeCalculation = (rowIndex) => debounceFunction(rowIndex);

  /**
   * @exports submitCheck 提交时的校验工具
   */
  const submitCheck = (param) => {
    let idfIM = true;
    const steam = param.procureDtoList;
    console.log(param);
    for (let a = 0; a <= steam.length - 1; a++) {
      if (isNullPm(steam[a].type)) {
        notification.warning(`新编号${a + 1}的采购单别必须选择!`);
        idfIM = false;
        break;
      }
      if (isNullPm(steam[a].supplier)) {
        notification.warning(`新编号${a + 1}的供应商必须选择!`);
        idfIM = false;
        break;
      }
      // if (isNullPm(steam[a].payment)) {
      //   notification.warning(`新编号${a + 1}的付款条件必须选择!`);
      //   idfIM = false;
      //   break;
      // }
    }
    return idfIM;
  };

  /**
   * @exports exchangeRateAcquisition 美元汇率获取
   */
  const exchangeRateAcquisition = () => {
    cmsmgLatestExchangeRate({ coinType: 'USD' }).then((res: any) => {
      if (res.code == 200) {
        base.exchangeRate = res.data;
      }
    });
  };

  /**
   * @exports amountData 金额总统计器
   */
  const amountData = () => {
    let purchaseAmount: any = 0,
      totalAmount: any = 0,
      totalTax: any = 0,
      totalNumber: any = 0;
    base.topTitle.map((res: any) => {
      if (isNullPm(res.purchaseAmount) || isNaN(res.purchaseAmount)) res.purchaseAmount = 0;
      if (isNullPm(res.totalAmount) || isNaN(res.totalAmount)) res.totalAmount = 0;
      if (isNullPm(res.totalTax) || isNaN(res.totalTax)) res.totalTax = 0;
      if (isNullPm(res.totalNumber) || isNaN(res.totalNumber)) res.totalNumber = 0;

      purchaseAmount = relativeAddition({ x: purchaseAmount, y: res.purchaseAmount });
      totalAmount = relativeAddition({ x: totalAmount, y: res.totalAmount });
      console.log(res.totalTax);
      totalTax = relativeAddition({ x: totalTax, y: res.totalTax });
      totalNumber = relativeAddition({ x: totalNumber, y: res.totalNumber });
    });
    base.amountOption = [
      {
        label: '含税总金额',
        value: totalAmount,
      },
      {
        label: '不含税总金额',
        value: purchaseAmount,
      },
      {
        label: '税额',
        value: totalTax,
      },
      {
        label: '数量总计',
        value: totalNumber,
      },
    ];
  };
  /**
   * @exports purchasingStaff 采购人员获取
   */
  const purchasingStaff = () => {
    cmsmvPurchaseStaffList('').then((res: any) => {
      if (res.code == 200) {
        base.purchasingOption = res.data;
      }
    });
  };

  /**
   * @exports mergeWithSuppliersDocuments 同供应商同单据合并
   */
  const mergeWithSuppliersDocuments = () => {
    base.singleDataList = conformToSteam(deepCopy(base.singleDataList));
  };

  /**
   * @exports remarkProcessing 单身备注处理
   */
  const remarkProcessing = (steam: any) => {
    steam.map((res: any) => {
      res.remark = '';
      res.remark = res.remarkpsan.join('、');
    });
    return steam;
  };

  /**
   * @exports purchasingPersonnelDataLoading 采购人员数据载入
   */
  const purchasingPersonnelDataLoading = () => {};

  /**
   * @exports cmsnaPurchasenpm
   */
  const cmsnaPurchasenpm = () => {
    cmsnaPurchaseVoList('').then((res: any) => {
      if (res.code == 200) {
        base.paymentTerms = res.data;
      }
    });
  };

  /**
   * @exports  playPombupm 付款条件绑定
   */
  const playPombupm = (param, rowIndex) => {
    base.topTitle[rowIndex].payment = param.paymentTermName;
  };
  return {
    base,
    init,
    menuConfig,
    selectAllChangeEvent,
    selectChangeEvent,
    vendorDataPartition,
    filterMethod,
    inputTion,
    clickSupplier,
    clickTaxCategory,
    contextMenuClickEvent,
    menuBodyConfig,
    contextMenuBodyClickEvent,
    bodySupplierView,
    clickValueNom,
    creatorPurtcAdd,
    clickCurrency,
    timeCalculation,
    purchasingStaff,
    remarkProcessing,
    clickCategoriesTaxes,
    clickTaxRate,
    ruleLoading,
    playPombupm,
  };
}
